﻿const Koa = require('koa')
const app = new Koa()


const views = require('koa-views')
const json = require('koa-json')
const onerror = require('koa-onerror')
const bodyparser = require('koa-bodyparser')
const logger = require('koa-logger')
const render = require('koa-ejs');

const net = require('net');
const socket = require('./lib/socket')
const record = require('./lib/record')

const path = require('path');

const index = require('./routes/index')
const users = require('./routes/users')
const apiUsers = require('./routes/api/users')
const geek = require('./routes/geek')

const setup = require('./lib/setup')();
const pinyin = require("node-pinyin");
const dictionary = require("./service/dictionary");

render(app, {
    root: path.join(__dirname, 'views'),
    layout: false,
    viewExt: 'html',
    cache: false,
    debug: false
});


// error handler
onerror(app)  
socket.respManager.addHandler(require('./service/api/cabines/resp/areaColumnConfiguration'));
socket.respManager.addHandler(require('./service/api/cabines/resp/initialStatus'));
socket.respManager.addHandler(require('./service/api/cabines/resp/temperatureAndHumidity'));
socket.respManager.addHandler(require('./service/api/cabines/resp/activeColumnPositions'));
socket.respManager.addHandler(require('./service/api/cabines/resp/activeColumnStatus'));
socket.respManager.addHandler(require('./service/api/cabines/resp/callback'));
socket.respManager.addHandler(require('./service/api/cabines/resp/close'));
socket.respManager.addHandler(require('./service/api/cabines/resp/open'));
socket.respManager.addHandler(require('./service/api/cabines/resp/stop'));







console.log("restart");
app.use(async (ctx,next)=>{
    ctx.state.socket = socket;
     
	//console.log(1);
	await next();
	//console.log(ctx.query.rest);
    if(ctx.query.resp != undefined){
        ctx.body = socket.respManager.result();
    }
})


// middlewares
app.use(bodyparser({
  enableTypes:['json', 'form', 'text']
}))
app.use(json())
app.use(logger())
app.use(require('koa-static')(__dirname + '/public'))

app.use(views(__dirname + '/views', {
  extension: 'pug'
}))

// logger
app.use(async (ctx, next) => {


  const start = new Date()
  await next()
  const ms = new Date() - start
})

// routes
app.use(index.routes(), index.allowedMethods())
app.use(users.routes(), users.allowedMethods())
app.use(apiUsers.routes(), apiUsers.allowedMethods())
app.use(geek.routes(), geek.allowedMethods())

// error-handling
app.on('error', (err, ctx) => {
  console.error('server error', err, ctx)
});

module.exports = app